package com.carhailing.auth.service.impl;

import com.alibaba.fastjson.JSON;
import com.carhailing.auth.feign.SystemFeign;
import com.carhailing.auth.service.AuthService;

import com.carhailing.common.constants.JwtConstants;
import com.carhailing.common.constants.TokenConstants;
import com.carhailing.common.domain.response.TokenDto;
import com.carhailing.common.domain.response.SysUserDto;
import com.carhailing.common.result.Result;
import com.carhailing.common.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Random;
import java.util.UUID;

/**
 * @Author：作者姓名
 * @Package：com.mj.auth.service.impl
 * @Project：g5_zuoye14
 * @name：AuthServiceImpl
 * @Date：2024/5/9 17:29
 */
@Service
public class AuthServiceImpl implements AuthService {
    @Autowired
    private SystemFeign systemFeign;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private HttpServletRequest servletRequest;

    @Override
    public Result<TokenDto> dologin(SysUserDto user) {
        Result<SysUserDto> getcode = systemFeign.getcode(user.getUserphone());
        SysUserDto user1 = getcode.getData();
        if (null ==user1){
           return Result.error("手机号错误");
        }
       if (!user1.getUserpwd().equals(user.getUserpwd())){
           return Result.error("密码错误");
       }

        HashMap<String, Object> hashMap = new HashMap<>();
        String uuid = UUID.randomUUID().toString();
        hashMap.put(JwtConstants.USER_KEY,uuid);
        String token = JwtUtils.createToken(hashMap);
        TokenDto restoken = new TokenDto();
        restoken.setToken(token);
        redisTemplate.opsForValue().set(JwtConstants.USER_KEY+uuid, JSON.toJSONString(user1));
        return Result.success(restoken);
    }

    @Override
    public Result<SysUserDto> info() {
        String token = servletRequest.getHeader(TokenConstants.TOKEN);
        String userKey = JwtUtils.getUserKey(token);
        String user = redisTemplate.opsForValue().get(JwtConstants.USER_KEY + userKey);
        SysUserDto user1 = JSON.parseObject(user, SysUserDto.class);
        return Result.success(user1);
    }
}
